<template>
  <div class="curriculum">
    <div class="curriculum-main-left">
      <div>
        <JobIntention :intention="resumeData.intention" :postData="postData" :cities="cities" :monthlyfrom="monthlyfrom"
          @save="saveWorkExperienceForm" />
        <WorkExperience :work_experience="resumeData.work_experience" @save="saveWorkExperienceForm" />
        <ProjectExperience :project_experience="resumeData.project_experience" @save="saveWorkExperienceForm" />
        <EducationExperience :education="resumeData.education" @save="saveWorkExperienceForm" />
        <AdditionalInfo :attach_info="resumeData.attach_info" @save="saveWorkExperienceForm" />
      </div>
    </div>
    <div class="curriculum-main-right">
      <div>
        <div class="title">
          <div>基本信息</div>
          <div class="text-custom-text text-[14px] flex items-center cursor-pointer" @click="toEditInfo"
            v-if="!isShowEditInfo">
            <img src="@/assets/images/edit-line.png" alt="" srcset="" class="mr-1 font-normal">
            编辑
          </div>
        </div>
        <div v-if="!isShowEditInfo">
          <div class="flex items-center">
            <div class="w-[56px] h-[80px] mr-[12px] upload_warp">
              <div class="w-[56px] h-[80px] camera_fill_warp" @click="triggerFileInput">
                <img class="camera_fill" src="@/assets/images/camera-fill.png" alt="">
              </div>
              <img class="w-[56px] h-[80px] mr-[12px]" :src="userInfo.photo" alt="">
              <input type="file" ref="fileInput" style="display:none;" @change="uploadFile">
            </div>
            <div>
              <div style="font-weight: bold;">{{ userInfo.name }}</div>
              <div class="leading-6">
                <span class="mr-[18px]">{{ userInfo.sex == 1 ? '男' : '女' }}</span>
                <span>{{ userInfo.age }}岁</span>
              </div>
              <div>{{ userInfo.contact_phone }}</div>
            </div>
          </div>
          <div class="flex">
            <img src="../../assets/home/building.png" alt="" class="building">
            <div class="text-custom-text">{{ userInfo.company_name }}</div>
          </div>
          <div class="flex">
            <img src="../../assets/home/home-6l.png" alt="" class="building">
            <div class="text-custom-text">{{ areaNames }}{{ userInfo.address }}</div>
          </div>
        </div>
        <div v-else>
          <!-- <div>
            <div>证件照</div>
            <div class="w-[56px] h-[80px] mr-[12px] upload_warp">
              <div class="w-[56px] h-[80px] camera_fill_warp" @click="triggerFileInput">
                <img class="camera_fill" src="@/assets/images/camera-fill.png" alt="">
              </div>
              <img class="w-[56px] h-[80px] mr-[12px]" :src="userInfo.photo" alt="">
              <input type="file" ref="fileInput" style="display:none;" @change="uploadFile">
            </div>

          </div>
          <div>
            <div>姓名</div>

          </div> -->
          <el-form :model="editInfoForm" ref="ruleFormRef" label-width="auto" label-position="top" class="demo-ruleForm" :show-message="false">
            <el-form-item label="证件照" prop="photo" required>
              <div class="w-[56px] h-[80px] mr-[12px] upload_warp">
                <div class="w-[56px] h-[80px] camera_fill_warp" @click="triggerFileInput">
                  <img class="camera_fill" src="@/assets/images/camera-fill.png" alt="">
                </div>
                <img class="w-[56px] h-[80px] mr-[12px]" :src="editInfoForm.photo" alt="">
                <input type="file" ref="fileInput" style="display:none;" @change="uploadFile">
              </div>
            </el-form-item>
            <el-form-item label="姓名" prop="name" required>
              <el-input v-model="editInfoForm.name" />
            </el-form-item>
            <el-form-item label="性别" prop="sex" required>
              <el-select v-model="editInfoForm.sex" placeholder="请选择性别">
                  <el-option v-for="item in sexOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="年龄" prop="age" required>
              <el-input v-model="editInfoForm.age" />
            </el-form-item>
            <el-form-item label="手机号" prop="contact_phone" required>
              <el-input v-model="editInfoForm.contact_phone" />
            </el-form-item>
            <el-form-item label="单位" prop="company_name" required>
              <el-input v-model="editInfoForm.company_name" />
            </el-form-item>
            <el-form-item label="地址" required>
              <el-form-item prop="area" required>
                <el-cascader class="mb-4" v-model="editInfoForm.area" :options="ChinaCitys" :props="cascaderProps"
                clearable placeholder="请选择地区" />
              </el-form-item>
              <el-form-item>
                <el-input v-model="editInfoForm.address" placeholder="请输入详细地址"></el-input>
              </el-form-item>
            </el-form-item>
            <el-form-item>
              <el-button @click="resetForm(ruleFormRef)">取消</el-button>
              <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div>
        <div class="title mgt">教育平台能力值</div>
        <div class="right-box flex">
          <div class="flex1">总能力值</div>
          <div class="num">{{ details.ability }}</div>
        </div>
        <div class="flex flex-wrap">
          <div class="right-zhi" v-for="(item, index) in details.details" :key="item.score">{{ item.name }}：{{
            item.score
          }}</div>
        </div>
      </div>
      <div>
        <div class="title mgt">能力证书</div>
        <div class="honor-main flex flex-wrap">
          <template v-for="(item, index) in certData.items" :key="item.id">
            <div class="honor-main-list" v-if="item.job">
              <div class="honor-main-list-bg"></div>
              <div>{{ item.job.name }}</div>
            </div>
          </template>

        </div>
      </div>
    </div>
  </div>

  <Preview :message="resumeData" :details="details" :certData="certData" :userInfo="userInfo" :previewShow="previewData"
    :areaNames="areaNames" v-if="previewData" @close-preview="handleClose" />
</template>
<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import ChinaCitys from '@/utils/ChinaCitys.json';
import { userApi } from '@/api/modules/user.js';
import { ElMessage } from 'element-plus';
import cityData from '@/utils/city-data.json';
import monthlyPay from '@/utils/monthly-pay.json';
import { useUserStore } from '@/stores/user';
import { TokenUtil } from '@/utils/common'
import JobIntention from '@/components/vitae/JobIntention.vue'
import WorkExperience from '@/components/vitae/WorkExperience.vue'
import ProjectExperience from '@/components/vitae/ProjectExperience.vue'
import EducationExperience from '@/components/vitae/EducationExperience.vue'
import AdditionalInfo from '@/components/vitae/AdditionalInfo.vue'
import Preview from '@/components/vitae/Preview.vue'
import axios from 'axios';
const props = defineProps({
  previewData: {
    type: Boolean,
    required: false,
    default: null
  },
  isResumePublic: Boolean
});
watch(
  () => props.isResumePublic,
  async (newValue) => {
    try {
      if (newValue !== undefined) {
        resumeData.value.is_open = newValue
        ResumeSave()
      }

    } catch (error) {
      console.error('保存简历公开状态失败:', error);
    }
  },
  { immediate: false } // 如果需要在组件初始化时立即执行一次，将此选项设为 true
);
const userStore = useUserStore();
const userInfo = computed(() => userStore.userInfo);
const monthlyfrom = ref(monthlyPay)
const cities = ref(cityData);
const postData = ref([])
const certData = ref([])
const details = ref([])
const fileInput = ref(null);
const isShowEditInfo = ref(false)
const editInfoForm = ref({})
const cascaderProps = {
  value: 'id',
  label: 'name',
  children: 'children',
}
const sexOptions = [
  {
    value: '0',
    label: '女',
  },
  {
    value: '1',
    label: '男',
  }
]
const ruleFormRef = ref()

const emit = defineEmits(['close-preview']);
const handleClose = () => {
  emit('close-preview');
};
const resumeData = ref({
  project_experience: [],
  attach_info: [],
  work_experience: [],
  education: [],
  intention: {
    post: {},
    salary: ['', ''],
    city: []
  },
  is_open: false
})

const areaNames = ref('');

onMounted(() => {
  areaNames.value = getNamesByIds(userInfo.value.area);
  fetchData();
  getStudentUserAbilityData()
  getStudentCertData()
  Child_optionsData();
});
// 通过ID数组查询对应的名称
const getNamesByIds = (ids) => {
  if (!ids || !Array.isArray(ids)) return [];

  const names = [];

  // 遍历每个ID进行查询
  for (const id of ids) {
    // 递归查找函数
    const findNameById = (data, targetId) => {
      for (const item of data) {
        if (item.id === targetId) {
          return item.name;
        }

        if (item.children && item.children.length > 0) {
          const foundName = findNameById(item.children, targetId);
          if (foundName) return foundName;
        }
      }
      return null;
    };

    const name = findNameById(ChinaCitys, id);
    if (name) names.push(name);
  }

  return names.join('');
};
const Child_optionsData = async () => {
  try {
    const data = await userApi.getChildOptions({
      dtype: 'job'
    });
    postData.value = data
  } catch (err) {
    console.log('Failed to fetch data:', err);
  }
}

const fetchData = async () => {
  try {
    const data = await userApi.getStudentResume();
    const { project_experience, attach_info, work_experience, education, intention } = data
    resumeData.value = {
      project_experience: project_experience || [],
      attach_info: attach_info || [],
      work_experience: work_experience || [],
      education: education || [],
      intention: intention || {
        post: { name: '' },
        salary: ['', ''],
        city: []
      },
      is_open: data.is_open
    }
  } catch (err) {
    console.log('Failed to fetch data:', err);
  }
};

// 方法：保存指定索引的工作经历表单项
async function saveWorkExperienceForm(item) {
  resumeData.value[item.type] = item.data
  const { intention } = resumeData.value || {}
  if (!intention.post.id) {
    ElMessage.error('求职意向必填!');
  }
  // return
  try {
    ResumeSave()
  } catch (error) {
    ElMessage.error('表单验证失败:', error);
  }
}
const getStudentCertData = async () => {
  try {
    const data = await userApi.getStudentCert({
      page: 1,
      pageSize: 999999
    });

    certData.value = data
  } catch (err) {
    console.log('Failed to fetch data:', err);
  }
};
const getStudentUserAbilityData = async () => {
  try {
    const data = await userApi.getStudentUserAbility();
    details.value = data

  } catch (err) {
    console.log('Failed to fetch data:', err);
  }
};

//提交简历信息接口
const ResumeSave = async () => {
  userApi.studentResumeSave(resumeData.value).then(res => {
    ElMessage.success('保存成功');
  });
}

const backgroundImages = {
  S: new URL('@/assets/home/jin.png', import.meta.url).href,
  A: new URL('@/assets/home/yin.png', import.meta.url).href,
  B: new URL('@/assets/home/tong.png', import.meta.url).href
}
const textColor = {
  S: '#A57C00',
  A: '#87888A',
  B: '#B56706',
}
//编辑基本信息
const toEditInfo = () => {
  isShowEditInfo.value = true
  editInfoForm.value = JSON.parse(JSON.stringify(userInfo.value))
}

const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (!valid) {
      ElMessage.error('请填写完整信息!')
    }else {
      userApi.updateUserInfo({
        photo: editInfoForm.value.photo,
        name: editInfoForm.value.name,
        sex: editInfoForm.value.sex,
        age: editInfoForm.value.age,
        contact_phone: editInfoForm.value.contact_phone,
        company_name: editInfoForm.value.company_name,
        area: editInfoForm.value.area,
        address: editInfoForm.value.address,
      }).then(res => {
        isShowEditInfo.value = false
        areaNames.value = getNamesByIds(editInfoForm.value.area);
        getFetchUserInfo()
        ElMessage.success('信息保存成功')
      });
    }
  })
}

//获取用户信息
const getFetchUserInfo = async () => {
  try {
    await userStore.fetchUserInfo();
  } catch (err) {
    console.log('Failed to fetch data:', err);
  }
};

const resetForm = (formEl) => {
  if (!formEl) return
  isShowEditInfo.value = false
  formEl.resetFields()
}

// 触发文件选择对话框的方法
const triggerFileInput = () => {
  fileInput.value.click();
};

//上传证件照
const uploadFile = async (event) => {
  const file = event.target.files[0];
  if (!file) return;

  // 创建 FormData 对象并附加文件
  const formData = new FormData();
  formData.append('file', file);
  const modelDir = 'aiedu';
  try {
    // 使用模板字符串构建 URL 并发送 POST 请求
    const { data } = await axios.post(
      `${import.meta.env.VITE_APP_BASE_API}/upload/minio/${modelDir}`,
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data',
          'authorization': `${TokenUtil.getToken()}`
        },
      }
    );
    userInfo.value.photo = data.data.file_url;
    editInfoForm.value.photo = data.data.file_url;
  } catch (error) {
    console.error('证件照上传失败:', error);
  }
};
</script>
<style lang="scss" scoped>
.curriculum {
  display: flex;
  padding-top: 24px;
  height: 100%;

  .mgt {
    margin-top: 24px;
  }

  .mainlist-hovers {
    background-color: #FAFAFA;
    cursor: pointer;
    border-radius: 6px 6px 6px 6px;
    padding: 10px 16px;
    margin-top: 20px;

    :deep(.el-textarea__inner) {
      height: 120px;
      resize: none;
    }

    :deep(.el-date-editor) {
      width: 123px !important;
    }

    :deep(.el-input__wrapper) {
      width: 278px;
    }

    :deep(.el-select) {
      width: 278px;
    }

    .yuexins {
      margin-left: 20px !important;
    }

    .yuexin {
      .hang {
        margin: 0 12px;
      }

      :deep(.el-select) {
        width: 123px;
      }
    }
  }

  .mainlist-hover {
    padding: 10px;
    font-family: MiSans, MiSans;
    font-weight: 400;
    font-size: 14px;

    .bianji {
      color: #33A0FF;
      margin-left: 20px;

      .delnum {
        color: #FC474C;
      }

      img {
        width: 16px;
        height: 16px;
        margin-right: 6px;
        margin-top: 5px;
      }

      .del {
        margin-left: 15px;
        margin-top: 10px;
      }
    }
  }

  .mainlist-hover:hover {
    background-color: #FAFAFA;
    cursor: pointer;
    border-radius: 6px 6px 6px 6px;
  }

  .title {
    font-family: MiSans, MiSans;
    font-weight: bold;
    font-size: 18px;
    color: #33A0FF;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;

    .add {
      width: 20px;
      height: 20px;
      cursor: pointer;
      // margin-top: 10px;
    }
  }

  .curriculum-main-right {
    padding-left: 24px;
    font-size: 13px;
    line-height: 35px;
    width: 300px;
    overflow: auto;
    padding-bottom: 20px;

    .upload_warp {
      cursor: pointer;
      position: relative;

      .camera_fill_warp {
        position: absolute;
        top: 0;
        left: 0;
        background: rgba(0, 0, 0, 0.3);
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
      }

      &:hover {
        .camera_fill_warp {
          opacity: 1;
        }
      }
    }

    .honor-main {
      font-family: MiSans, MiSans;
      font-weight: 400;
      font-size: 14px;
      color: rgba(0, 0, 0, 0.88);
      line-height: 22px;
      justify-content: space-between;

      .honor-main-list {
        margin-top: 16px;
        text-align: center;
        line-height: 38px;
      }

      .honor-main-list-bg {
        width: 112px;
        text-align: left !important;
        height: 84px;
        background-image: url(../../assets/home/jin.png);
        background-size: 100% 100%;
        box-sizing: border-box;
        padding: 24px 16px;
        line-height: 30px !important;
        color: #A57C00;
        font-size: 16px;
        font-family: DingTalk JinBuTi, DingTalk JinBuTi;
        font-weight: 400;

        .num {
          font-weight: bold;
          font-size: 22px;
        }
      }
    }

    .right-zhi {
      font-family: MiSans, MiSans;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.45);
      font-size: 14px;
      line-height: 38px;
      margin-right: 15px;
    }

    .right-box {
      height: 44px;
      background: linear-gradient(315deg, #E9F5FF 0%, #F4FAFF 100%);
      border-radius: 6px 6px 6px 6px;
      box-sizing: border-box;
      padding: 0 16px;
      font-family: MiSans, MiSans;
      font-weight: 400;
      font-size: 14px;
      color: rgba(0, 0, 0, 0.65);
      line-height: 44px;

      .num {
        font-family: DingTalk JinBuTi, DingTalk JinBuTi;
        font-weight: 400;
        color: #9DD1FF;
        font-size: 20px;
      }
    }

    .building {
      width: 16px;
      height: 16px;
      margin-right: 10px;
      margin-top: 10px;
    }

    .gun {
      margin: 10px 15px 0;
      width: 1px;
      height: 14px;
      background: rgba(0, 0, 0, 0.25);
      border-radius: 0px 0px 0px 0px;
    }
  }

  .curriculum-main-left {
    box-sizing: border-box;
    font-family: MiSans, MiSans;
    font-weight: 400;
    font-size: 16px;
    flex: 1;
    overflow: auto;
    padding-bottom: 20px;

    color: rgba(0, 0, 0, 0.88);

    .main-jinglist {
      font-weight: bold;
      line-height: 35px;

      .left-miaoshu {
        display: flex;
        font-weight: bold;
        font-size: 14px;
        color: rgba(0, 0, 0, 0.88);

        p {
          flex: 1;
          font-weight: 400;
          padding-left: 12px;
        }
      }

      .yuan {
        font-weight: 400;
        font-size: 16px;
        color: rgba(0, 0, 0, 0.65);
      }

      .time {
        font-size: 14px;
        color: rgba(0, 0, 0, 0.45);
        font-weight: 400;
      }
    }

    .name {
      padding-right: 24px;
      font-size: 14px;
    }

    .left-money {
      padding: 0 24px;
      border-left: 1px solid #BFBFBF;
      font-size: 14px;

      .city {
        margin-right: 5px;
      }

      img {
        width: 16px;
        height: 16px;
        margin-top: 2px;
        margin-right: 8px;
      }
    }
  }
}
</style>